'''
Author: your name
Date: 2022-04-26 04:41:40
LastEditTime: 2022-04-26 05:33:05
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: \ICBC\ICBC_nonlinear_optimization\tools\read_config\atm_config.py
'''
import datetime
import pathlib

'''
有关数据处理方面的问题，
需要将所需要加载的数据放到DATA文件下
包括：
1、未来7天各ATM机的取款预测矩阵：D_1，7*72（工行提供计算函数）
2、未来7天各ATM机的存款预测矩阵：D_2，7*72（工行提供计算函数）
3、第0天（开始加钞前1天）各ATM机库存现金矩阵：I_0，1*72
4、经过百度地图API智能推荐得到的包括现金中心和72台ATM机的距离矩阵:distance_list, 73*73
5、各ATM机按照现金使用率高低统计的ATM机分类表：c_label
6、各ATM机第0天的清机表：cutoff_list
7、根据历史数据统计得到的各ATM机日均净取款aver_1

'''

import os

import numpy as np
import pandas as pd


class ATMLoadData():
    def __init__(self, data_folder_root=None, val=False):
        withdraw_history = []
        deposit_history = []
        h_withdraw_history = []
        h_deposit_history = []
        all_no = np.array(
            pd.read_csv(os.path.join(data_folder_root, 'device_info_1.csv', )).values[:, 0],
            dtype=np.uint)

        for file_name in os.listdir(os.path.join(data_folder_root, 'RAW_data')):
            cur_no = pd.read_excel(os.path.join(data_folder_root, 'RAW_data', file_name))['机号'].values
            if cur_no[0] not in set(all_no):
                continue
            sel = ~np.isnan(cur_no)
            withdraw = pd.read_excel(os.path.join(data_folder_root, 'RAW_data', file_name))['取款'][sel].values
            withdraw_history.append(withdraw)
            deposit = pd.read_excel(os.path.join(data_folder_root, 'RAW_data', file_name))['存款'][sel].values
            deposit_history.append(deposit)

        sel_len = np.min([x.shape[0] for x in withdraw_history])
        self.withdraw_history = np.array([x[:sel_len] for x in withdraw_history], dtype=np.float).T
        self.deposit_history = np.array([x[:sel_len] for x in deposit_history], dtype=np.float).T
        self.data_folder_root = data_folder_root

        if val:
            data_time = (
                        datetime.datetime.strptime(os.path.basename(data_folder_root), "%Y-%m-%d") + datetime.timedelta(
                    6)).strftime('%Y-%m-%d')
            hist_data = pathlib.Path(os.path.join(
                os.path.dirname(data_folder_root),
                data_time,
                'RAW_data'
            )).as_posix()
            for file_name in os.listdir(hist_data):
                cur_no = pd.read_excel(os.path.join(hist_data, file_name))['机号'].values
                if cur_no[0] not in set(all_no):
                    continue
                h_withdraw = pd.read_excel(os.path.join(hist_data, file_name))['取款'].values
                h_withdraw_history.append(h_withdraw)

                h_deposit = pd.read_excel(os.path.join(hist_data, file_name))['存款'].values
                h_deposit_history.append(h_deposit)

            self.w_hist = []
            for i in range(7):
                cur_d = pathlib.Path(os.path.join(
                    os.path.dirname(data_folder_root),
                    (datetime.datetime.strptime(os.path.basename(data_folder_root), "%Y-%m-%d") + datetime.timedelta(
                        i)).strftime('%Y-%m-%d'),
                    'w_0.csv'
                )).as_posix()
                self.w_hist.append(np.array(pd.read_csv(cur_d, dtype=float, header=None)))

            self.h_withdraw_history = np.array([x[:sel_len] for x in h_withdraw_history], dtype=np.float).T
            self.h_deposit_history = np.array([x[:sel_len] for x in h_deposit_history], dtype=np.float).T
            self.w_hist = np.hstack(self.w_hist).T

        # 未来8天各ATM机的取款预测矩阵，8*72
        self.D = np.array(
            pd.read_csv(os.path.join(self.data_folder_root, 'forecast_list.csv'), dtype=float, header=None))
        self.D[1:] = self.D[1:] - self.D[:-1]
        self.D = self.D[:7]

        # 第0天（开始加钞前1天）各ATM机库存现金矩阵，1*72

        self.cutoff_limit = np.array(
            pd.read_csv(os.path.join(self.data_folder_root, 'cutoff_limit.csv'), dtype=int, header=None))

        self.I_0 = np.array(pd.read_csv(os.path.join(self.data_folder_root, 'I_0.csv'), dtype=float, header=None))
        self.w_0 = np.array(pd.read_csv(os.path.join(self.data_folder_root, 'w_0.csv'), dtype=float, header=None))
        # self.loc = np.array(pd.read_csv(os.path.join(self.data_folder_root, 'OP_1.csv')).values[:, 3:], dtype=np.float)
        self.max_cap = np.array(
            pd.read_csv(os.path.join(self.data_folder_root, 'device_info_1.csv', )).values[:, 2],
            dtype=np.uint)

        # 经过百度地图API智能推荐得到的包括现金中心和72台ATM机的距离矩阵，大小73*73
        # self.distance_list = np.array(pd.read_csv(os.path.join(self.data_folder_root, 'distance_list.csv'), dtype=float, header=None))

        # 各ATM机的分类
        m1, m2 = np.mean(self.withdraw_history, 0), np.mean(self.deposit_history, 0)

        # 各ATM机第0天的清机表
        self.cutoff_list = np.array(
            pd.read_csv(os.path.join(self.data_folder_root, 'cutoff_list.csv'), dtype=int, header=None))

        # 各ATM机日均净取款量
        self.std_D2 = np.std(self.deposit_history, 0)
        self.avg_D2 = m2
        self.aver_1 = np.maximum(100, m1 - m2)

        self.load_success()

    def load_success(self):
        print("Load data successfully!!!")


if __name__ == '__main__':
    DATA_ROOT = os.path.join(os.getcwd(), '../DATA')
    DATA = ATMLoadData(DATA_ROOT)

    D_1 = DATA.D_1
    D_2 = DATA.D_2
    D = D_1 - D_2
    I_0 = DATA.I_0.flatten()
    distance_list = DATA.distance_list
    c_label = DATA.c_label.flatten()
    aver_1 = DATA.aver_1.flatten()
    cutoff_list = DATA.cutoff_list.flatten()

    # 测试
    print(I_0)
